package com.xinxin.intelligenceexam.studyMenu.webH5;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

import com.xinxin.intelligenceexam.R;
import com.xinxin.intelligenceexam.activity.SplashActivity;

import butterknife.BindView;
import butterknife.ButterKnife;


public class WebH5Activity extends AppCompatActivity {

    private static final String TAG = "WebH5Activity";
    @BindView(R.id.wv_h5)
    WebView mWebView;
    @BindView(R.id.activity_web_h5)
    RelativeLayout mActivityWebH5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_h5);
        ButterKnife.bind(this);
        mWebView.loadUrl("file:///android_asset/test.html");
        //例如：加载网页
//        mWebView.loadUrl("http://www.baidu.com");
        initWebView();
    }

    private void initWebView() {
        WebSettings webSettings = mWebView.getSettings();
//        Android本地通过Java调用HTML页面中的JavaScript方法
        webSettings.setJavaScriptEnabled(true);
//        js调用Android本地Java方法
        mWebView.addJavascriptInterface(new JsInteration(), "android");
        //设置在当前页面打开url，而不是调用本机的浏览器
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                拦截HTML页面中的点击事件
                if (url.equals("file:///android_asset/test2.html")) {
                    Log.e(TAG, "shouldOverrideUrlLoading: " + url);
                    startActivity(new Intent(WebH5Activity.this, SplashActivity.class));
                    return true;
                } else {
                    mWebView.loadUrl(url);
                    return false;
                }
            }
        });
    }

    //Android系统调用有返回值js方法，如果调用无返回值（do方法）的可以直接：mWebView.loadUrl("javascript:do()");
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void onClick(View v) {

        mWebView.evaluateJavascript("sum(1,2)", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                Log.e(TAG, "onReceiveValue value=" + value);
            }
        });
    }

    public class JsInteration {

        @JavascriptInterface
        public String back() {
            return "hello world";
        }
    }
}
